/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.openbookformat.obffinder;

import java.io.IOException;
import java.util.Collection;
import java.util.logging.Logger;
import javax.swing.JEditorPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import org.apache.commons.lang.StringEscapeUtils;
import org.openide.util.Exceptions;
import org.openide.util.LookupEvent;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.util.Lookup;
import org.openide.util.LookupListener;
import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.openbookformat.obffinder//OBFFindResultView//EN",
autostore = false)
public final class OBFFindResultViewTopComponent extends TopComponent {

    private static OBFFindResultViewTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "OBFFindResultViewTopComponent";

    public OBFFindResultViewTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(OBFFindResultViewTopComponent.class, "CTL_OBFFindResultViewTopComponent"));
        setToolTipText(NbBundle.getMessage(OBFFindResultViewTopComponent.class, "HINT_OBFFindResultViewTopComponent"));
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));

        lookupResult = Utilities.actionsGlobalContext().lookupResult(
                FindResult.class);

        lookupResult.addLookupListener(new LookupListener() {

            @Override
            public void resultChanged(LookupEvent ev) {
                Collection c = lookupResult.allInstances();
                findResult = c.isEmpty()? null:
                    (FindResult) c.iterator().next();
                findResultChanged(findResult);
            }
        });

    }

    int offset = 25;
    private void findResultChanged(FindResult findResult) {
        System.out.println("FindResult:" + findResult);
        if (findResult == null)
            return;

        try {
            StyledDocument doc = findResult.getEditorCookie().openDocument();
            int findStart = 0;
            int endOffset = offset;
            int findEnd = doc.getLength() -1;
            if (findResult.getIndex() > offset)
                findStart = findResult.getIndex() - offset;
            if (findResult.getIndex() + offset < doc.getLength() - 1) {
                findEnd = findResult.getIndex() +  findResult.getFind().length() +  offset;
                endOffset = offset;
            } else {
                findEnd = doc.getLength() -1;
                endOffset = doc.getLength() - findResult.getIndex() -  findResult.getFind().length();
            }
            System.out.println("End Offset:" + endOffset);

            System.out.println("Doc:length:" + doc.getLength());
            System.out.println("findStart:" + findStart + ",findEnd:" + findEnd);

            System.out.println(findStart + ":" + findResult.getIndex());
            System.out.println(findResult.getIndex() + findResult.getFind().length() + ":" + findEnd);

            System.out.println("X:" + doc.getText(findStart, offset) );
            System.out.println("Y:" + findResult.getFind());
            System.out.println("Z:" + doc.getText(
                    findResult.getIndex() + findResult.getFind().length(), endOffset));
            
            jFind.setText("<html>" +
                    "<font color='blue'>" + StringEscapeUtils.escapeHtml(
                    doc.getText(findStart, offset)).replaceAll("\n", "<br/>") + "</font>" +
                    "<font color='red'>" + StringEscapeUtils.escapeHtml(
                    findResult.getFind()).replaceAll("\n", "<br/>") + "</font>" +
                    "<font color='blue'>" + StringEscapeUtils.escapeHtml(doc.getText(
                    findResult.getIndex() + findResult.getFind().length(), 
                    endOffset)).replaceAll("\n", "<br/>") + "</font>" + 
                    "</html>");
            
//            jFind.setText(doc.getText(findStart, offset) + 
//                    findResult.getFind() + "</font>" +
//                    doc.getText(
//                    findResult.getIndex() + findResult.getFind().length(), 
//                    endOffset));
            //
            
            
            jReplace.setText(findResult.getReplace());
            jIndex.setText(findResult.getIndex() + "");
            jSelected.setState(findResult.isSelected());

            if(findResult.getEditorCookie().getOpenedPanes() != null) {
                JEditorPane editorPane = findResult.getEditorCookie().getOpenedPanes()[0];
                editorPane.setSelectionStart(findResult.getIndex());
                editorPane.setSelectionEnd(findResult.getIndex() + findResult.getFind().length());
            }
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jIndex = new javax.swing.JTextField();
        jSelected = new java.awt.Checkbox();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jFind = new javax.swing.JEditorPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jReplace = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        jOffset = new javax.swing.JSpinner();

        setOpaque(true);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jLabel3.text")); // NOI18N

        jIndex.setEditable(false);
        jIndex.setText(org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jIndex.text")); // NOI18N

        jSelected.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jSelected.setLabel(org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jSelected.label")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jLabel4.text")); // NOI18N

        jFind.setContentType(org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jFind.contentType")); // NOI18N
        jFind.setEditable(false);
        jScrollPane1.setViewportView(jFind);

        jReplace.setColumns(20);
        jReplace.setRows(5);
        jScrollPane2.setViewportView(jReplace);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(OBFFindResultViewTopComponent.class, "OBFFindResultViewTopComponent.jLabel5.text")); // NOI18N

        jOffset.setModel(new javax.swing.SpinnerNumberModel(25, 5, 100, 5));
        jOffset.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jOffsetStateChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jOffset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                    .addComponent(jSelected, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jIndex, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jIndex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSelected, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jOffset, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jOffsetStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jOffsetStateChanged
        // TODO add your handling code here:
        offset = ((Integer) jOffset.getValue()).intValue();
        System.out.println("Offset:" + offset);
        findResultChanged(findResult);
    }//GEN-LAST:event_jOffsetStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JEditorPane jFind;
    private javax.swing.JTextField jIndex;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSpinner jOffset;
    private javax.swing.JTextArea jReplace;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private java.awt.Checkbox jSelected;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized OBFFindResultViewTopComponent getDefault() {
        if (instance == null) {
            instance = new OBFFindResultViewTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the OBFFindResultViewTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized OBFFindResultViewTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(OBFFindResultViewTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof OBFFindResultViewTopComponent) {
            return (OBFFindResultViewTopComponent) win;
        }
        Logger.getLogger(OBFFindResultViewTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    private FindResult findResult;
    private Lookup.Result lookupResult;
}
